from flask import  Blueprint,render_template,url_for,request,redirect
from models.House import House
from flask import Flask
import math
from sqlalchemy import and_, or_
bp = Blueprint('list_page',__name__,url_prefix='/')


@bp.route('/query', methods=['POST'])
def search_txt_info():
    per_page = 10
    page = request.form.get('page', 1, type=int)

    # 初始化查询
    query = House.query

    # 获取所有可能的查询参数
    addr = request.form.get('addr')
    rooms = request.form.get('rooms')
    area_min = request.form.get('area_min')
    area_max = request.form.get('area_max')
    price_min = request.form.get('price_min')
    price_max = request.form.get('price_max')
    facilities_str = request.form.getlist('facilities')
    print(facilities_str)
    # 构建查询条件
    conditions = []

    # 1. 处理地区搜索
    if addr:
        conditions.append(
            or_(
                House.address.contains(addr),
                House.region.contains(addr),
                House.block.contains(addr)
            )
        )

    # 2. 处理户型搜索
    if rooms:
        if rooms == "5室及以上":
            # 处理5室及以上的特殊情况
            conditions.append(
                or_(
                    House.rooms.like('5室%'),
                    House.rooms.like('6室%'),
                    House.rooms.like('7室%'),
                    House.rooms.like('8室%'),
                    House.rooms.like('9室%')
                )
            )
        else:
            conditions.append(House.rooms.like(f'{rooms}%'))

    # 3. 处理面积范围筛选
    if area_min:
        try:
            conditions.append(House.area >= float(area_min))
        except (ValueError, TypeError):
            pass

    if area_max:
        try:
            conditions.append(House.area <= float(area_max))
        except (ValueError, TypeError):
            pass

    # 4. 处理价格范围筛选
    if price_min:
        try:
            conditions.append(House.price >= float(price_min))
        except (ValueError, TypeError):
            pass

    if price_max:
        try:
            conditions.append(House.price <= float(price_max))
        except (ValueError, TypeError):
            pass
    # 5. 处理设施筛选
    if facilities_str:
        for facility in facilities_str:
            conditions.append(House.facilities.contains(facility))
    # 应用所有条件
    if conditions:
        query = query.filter(and_(*conditions))
    else:
        # 如果没有任何搜索条件，重定向到首页
        return redirect(url_for("index.index"))

    # 执行查询并分页
    result = query.order_by(House.publish_time.desc()) \
        .limit(per_page) \
        .offset((page - 1) * per_page) \
        .all()

    # 计算总页数
    total_count = query.count()
    total_num = math.ceil(total_count / per_page)

    # 构建查询字符串用于分页链接
    query_params = request.args.copy()
    if 'page' in query_params:
        del query_params['page']
    queryString = '&'.join([f"{k}={v}" for k, v in query_params.items()])

    return render_template(
        "search_list.html",
        house_list=result,
        page_num=page,
        total_num=total_num,
        queryString=queryString,
        addr=addr,
        rooms=rooms,
        area_min=area_min,
        area_max=area_max,
        price_min=price_min,
        price_max=price_max,
        facilities=facilities_str
    )

def deal_title_over(word):
    if len(word) > 15:

        return word[:15] + '...'  # 当房源标题长度大于15时，用省略号替换
    else:
        return word
def deal_direction(word):
    if len(word) == 0 or word is None:  # 房源朝向、交通条件为空时显示暂无信息
        return '暂无信息！'
    else:
        return word

bp.add_app_template_filter(deal_title_over, 'dealover')
bp.add_app_template_filter(deal_direction, 'dealdirection')


@bp.route('/list/pattern/<int:page>')
def return_new_list(page):
    #查询房源总数
    house_num = House.query.count()
    #计算总的页码数
    per_page = 10
    total_num = math.ceil(house_num / per_page) #向上取整
    result = (House.query.order_by(House.publish_time.desc())
              .limit(per_page).offset((page - 1) * per_page).all())
    return render_template('list.html',
                           house_list = result, page_num=page, total_num=total_num)



@bp.route('/list/hot_house/<int:page>')
def return_hot_list(page):
    #查询房源总数
    house_num = House.query.count()
    #计算总的页码数
    per_page = 10
    total_num = math.ceil(house_num / per_page) #向上取整
    result = (House.query.order_by(House.page_views.desc())
              .limit(per_page).offset((page - 1) * per_page).all())
    return render_template('list.html',
                           house_list = result, page_num=page, total_num=total_num)